﻿@model Xms.Web.Models.EditRoleButtonPermissionsModel

<div class="container-fluid">
    <div class="row" style="padding:5px 0px;">
        <div class="col-sm-11 btn-group" id="owners">
            <button type="button" class="btn btn-sm btn-default">类型：</button>
        </div>
    </div>
</div>
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">
            <a data-toggle="collapse"
               href="#collapseTwo">
                <strong id="rolename" class="text-primary">@Model.Role.Name</strong> - <strong>@app.PrivilegeTree?.LastOrDefault().DisplayName</strong>
            </a>
        </h3>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse in">
        <div class="panel-body">
            <form id="editform" class="form-horizontal" data-jsonajax="true" data-istip="true" action="/@(app.OrganizationUniqueName)/api/role/SaveRolePermissions" method="post">
                @Html.AntiForgeryToken()
                @Html.HiddenFor(x => x.RoleId)
                @Html.HiddenFor(x => x.ResourceName)
                <div class="form-group col-sm-12">
                    <div class="table-responsive">
                        <table class="table table-bordered table-condensed" id="entities">
                            <thead class="table-header">
                                <tr>
                                    <th class="xms-checker" checkertype="all"> <div class="btn"><strong>实体</strong></div></th>
                                    <th class="xms-checker" checkertype="cum">
                                        <div class="btn"><strong>表单</strong></div>
                                        <div class="pull-right" id="mask_dropdownmenu_7">
                                            <div class="dropdown">
                                                <button type="button" class="btn btn-link dropdown-toggle" id="mask_dropdownbtn" data-toggle="dropdown" aria-expanded="true">
                                                    <span class="caret"></span>
                                                </button>
                                                <ul class="dropdown-menu pull-right" role="menu" aria-labelledby="mask_dropdownbtn">
                                                    <li role="presentation">
                                                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckCol(this,true,true)">全选</a>
                                                    </li>
                                                    <li role="presentation">
                                                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckCol(this,true,false)">全不选</a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    </th>
                                    <th class="xms-checker" checkertype="cum">
                                        <div class="btn"><strong>列表头部</strong></div>
                                        <div class="pull-right" id="mask_dropdownmenu_7">
                                            <div class="dropdown">
                                                <button type="button" class="btn btn-link dropdown-toggle" id="mask_dropdownbtn" data-toggle="dropdown" aria-expanded="true">
                                                    <span class="caret"></span>
                                                </button>
                                                <ul class="dropdown-menu pull-right" role="menu" aria-labelledby="mask_dropdownbtn">
                                                    <li role="presentation">
                                                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckCol(this,true,true)">全选</a>
                                                    </li>
                                                    <li role="presentation">
                                                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckCol(this,true,false)">全不选</a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    </th>
                                    <th class="xms-checker" checkertype="cum">
                                        <div class="btn"><strong>列表行内</strong></div>
                                        <div class="pull-right" id="mask_dropdownmenu_7">
                                            <div class="dropdown">
                                                <button type="button" class="btn btn-link dropdown-toggle" id="mask_dropdownbtn" data-toggle="dropdown" aria-expanded="true">
                                                    <span class="caret"></span>
                                                </button>
                                                <ul class="dropdown-menu pull-right" role="menu" aria-labelledby="mask_dropdownbtn">
                                                    <li role="presentation">
                                                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckCol(this,true,true)">全选</a>
                                                    </li>
                                                    <li role="presentation">
                                                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckCol(this,true,false)">全不选</a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    </th>
                                    <th class="xms-checker" checkertype="cum">
                                        <div class="btn"><strong>单据体</strong></div>
                                        <div class="pull-right" id="mask_dropdownmenu_7">
                                            <div class="dropdown">
                                                <button type="button" class="btn btn-link dropdown-toggle" id="mask_dropdownbtn" data-toggle="dropdown" aria-expanded="true">
                                                    <span class="caret"></span>
                                                </button>
                                                <ul class="dropdown-menu pull-right" role="menu" aria-labelledby="mask_dropdownbtn">
                                                    <li role="presentation">
                                                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckCol(this,true,true)">全选</a>
                                                    </li>
                                                    <li role="presentation">
                                                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckCol(this,true,false)">全不选</a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    </th>
                                </tr>
                            </thead>
                            <tbody class="table-body"></tbody>
                        </table>
                    </div>
                </div>
                <nav class="navbar navbar-default navbar-fixed-bottom" role="navigation" id="body-footer">
                    <div class="navbar-form navbar-right" id="form-buttons" style="display:inline-block!important;">
                        <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-saved"></span> @app.T["save"]</button>
                        <button type="reset" class="btn btn-default"><span class="glyphicon glyphicon-refresh"></span> @app.T["reset"]</button>
                    </div>
                </nav>
            </form>
        </div>
    </div>
</div>
@section Header {
<style>
    .form-group input[type="checkbox"]{margin-left:-20px; margin-top:0;}
    .checkbox label, .radio label{padding-left: 28px;}
</style>
}
@section Scripts {
    <script src="/content/js/xms.utility.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="~/content/js//jquery-validate/jquery.validate.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/xms.web.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/xms.jquery.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/knockout-2.2.0.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/icheck/icheck.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/xms.metadata.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script>

        var ObjectId = @Html.Raw(Model.RoleObjectAccesses!= null ? Model.RoleObjectAccesses.Select(n=>n.ObjectId).ToList()?.SerializeToJson() : "[]");

        $(function () {
            bindEntities();
            loadResourceOwners();
        });

        function loadResourceOwners() {
            Xms.Web.GetJson(ORG_SERVERURL + "/api/security/ResourceOwners", null, function (data) {
                if (!data.IsSuccess) return;
                var items = JSON.parse(data.Content);
                var resourceName = $('#ResourceName').val().toLowerCase();
                var $container = $('#owners');
                $(items).each(function (i, n) {
                    var url = (n.uiendpoint || '/role/editrolepermissions') + '?roleid=' + $("#RoleId").val() + '&resourcename=' + n.modulename;
                    $container.append($('<button type="button" class="btn btn-sm ' + (resourceName == n.modulename.toLowerCase() ? 'btn-info' : 'btn-default') + '" data-url="' + url + '">' + n.modulelocalizedname + '</button>'));
                });
                $container.find('button').on('click', null, function () {
                    Xms.Web.Redirect($(this).attr('data-url'));
                });
            });
        }

        function bindEntities() {
            Xms.Schema.GetEntities(null, function (data) {
                if (data && data.length > 0) {
                    bindButtons(data);
                }
            });
        }
        function filterButtons(datas) {
            var res = [];
            $.each(datas, function (i,n) {
                if (n.children && n.children.length > 0) {
                    $.each(n.children, function (ii, nn) {
                        var showarea = 0;
                        if (nn.label == '表单') {
                            showarea = 1;
                        }else if (nn.label == '列表头部') {
                            showarea = 2;
                        }else if (nn.label == '列表行内') {
                            showarea = 3;
                        }else if (nn.label == '单据体') {
                            showarea = 4;
                        }
                        if (nn.children && nn.children.length > 0) {
                            $.each(nn.children, function (iii, nnn) {
                                nnn.showarea = showarea;
                                    res.push(nnn);
                               
                            });
                        }
                    });
                }
            });
            return res;
        }
        function bindButtons(entities) {
            Xms.Ajax.GetJson('/api/ribbonbutton/PrivilegeResource?authorizationEnabled=true', null, function (response) {
                if (response.IsSuccess) {
                    var data = JSON.parse(response.Content);
                    var tb = $('#entities');
                    var tbody = tb.find('tbody');
                    tbody.html();
                    if (entities && entities.length == 0) {
                        tbody.append('<tr><td colspan="5" style="font-size:18px; text-align:center;">没有数据</td></tr>');
                        return false;
                    }
                    allbuttons = [];
                    $(entities).each(function (i, entity) {
                        var buttons = $.grep(data, function (n, j) {
                            return n.groupid == entity.entityid;
                        });
                        console.log(entity.localizedname, buttons);
                        if (buttons && buttons.length > 0) {
                            allbuttons.push(buttons);
                        }
                        if (!buttons || buttons.length == 0) return true;
                        var html = "<tr>";
                        var FormButton = "<td>";
                        var ListHeadButton = "<td>";
                        var ListRowButton = "<td>";
                        var SubGridButton = "<td>";
                        buttons = filterButtons(buttons);
                        if (buttons && buttons.length > 0) {
                            html += '<td class="xms-checker" checkertype="col" data-name="' + entity.name + '">';
                            html += '<label class="btn"><strong>' + entity.localizedname + '</strong></label>';
                            html += '</td>';
                            $(buttons).each(function (j, button) {
                                var flag = button.id ? ($.inArray(button.id, ObjectId) != -1) : false;
                                if (button.showarea == 1) {
                                    FormButton += '<div class="checkbox">';
                                    FormButton += '<label for="ribbonbtn' + i + '_' + j + '"> ' +'<input type="checkbox" id="ribbonbtn'+i+'_'+j+'" name="ObjectId" value="' + button.id + '" ' + (flag ? " checked" : "") + ' /> ';
                                    FormButton +=  button.label + '</label>';
                                    FormButton += '</div>';
                                }
                                else if (button.showarea == 2) {
                                    ListHeadButton += '<div class="checkbox">';
                                    ListHeadButton += '<label for="ribbonbtn' + i + '_' + j + '"> ' + '<input type="checkbox" id="ribbonbtn' + i + '_' + j +'" name="ObjectId" value="' + button.id + '" ' + (flag ? " checked" : "") + ' /> ';
                                    ListHeadButton += button.label + '</label>';
                                    ListHeadButton += '</div>';
                                }
                                else if (button.showarea == 3) {
                                    ListRowButton += '<div class="checkbox">';
                                    ListRowButton += '<label for="ribbonbtn' + i + '_' + j + '"> ' + '<input type="checkbox" id="ribbonbtn' + i + '_' + j +'" name="ObjectId" value="' + button.id + '" ' + (flag ? " checked" : "") + ' /> ';
                                    ListRowButton +=  button.label + '</label>';
                                    ListRowButton += '</div>';
                                }
                                else if (button.showarea == 4) {
                                    SubGridButton += '<div class="checkbox">';
                                    SubGridButton += '<label for="ribbonbtn' + i + '_' + j + '"> ' +'<input type="checkbox" id="ribbonbtn' + i + '_' + j +'" name="ObjectId" value="' + button.id + '" ' + (flag ? " checked" : "") + ' /> ';
                                    SubGridButton += button.label + '</label>';
                                    SubGridButton += '</div>';
                                }
                            });

                            if (FormButton.indexOf("div") == -1) {
                                FormButton += '<div>';
                                FormButton += '<label for="Name">-</label>';
                                FormButton += '</div>';
                            }
                            if (ListHeadButton.indexOf("div") == -1) {
                                ListHeadButton += '<div>';
                                ListHeadButton += '<label for="Name"> -</label>';
                                ListHeadButton += '</div>';
                            }
                            if (ListRowButton.indexOf("div") == -1) {
                                ListRowButton += '<div>';
                                ListRowButton += '<label for="Name">-</label>';
                                ListRowButton += '</div>';
                            }
                            if (SubGridButton.indexOf("div") == -1) {
                                SubGridButton += '<div>';
                                SubGridButton += '<label for="Name">-</label>';
                                SubGridButton += '</div>';
                            }
                            FormButton += '</td>';
                            ListHeadButton += '</td>';
                            ListRowButton += '</td>';
                            SubGridButton += '</td></tr>';
                            tbody.append(html + FormButton + ListHeadButton + ListRowButton + SubGridButton);

                        }

                    });
                    if (allbuttons&& allbuttons.length==0) {
                        tbody.append('<tr><td colspan="5" style="font-size:18px;text-align:center;">没有数据</td></tr>');

                        return false;
                    }
                    //tbody.find('input[type="checkbox"]').iCheck({
                    //    checkboxClass: 'icheckbox_minimal-blue',
                    //    radioClass: 'iradio_minimal-blue',
                    //    increaseArea: '10%'
                    //})
                    bindEvent(tb);
                }
            });
        }

        function tablecheckCol(target,auto,flag) {
            var $this = $(target), $table = $this.parents('table:first');
            var $td = null;
            if ($this.get(0).tagName == 'th') {
                $td = $this;
            } else {
                $td = $this.parents('th:first');
            }
            var index = $td.index();
            var $tbody = $table.find('tbody');
            if (!auto) {
                var checked = $td.attr('data-checked');

                if (!checked || checked == '0') {
                    $td.attr('data-checked', 1);
                    $tbody.find('tr').each(function () {
                        var checks = $(this).find('td').eq(index).find('input[type="checkbox"]');
                        if (checks.length > 0) {
                            checks.prop('checked', true);
                           // checks.each(function () {
                           //     $(this).iCheck('check');
                           // })
                        }
                    });
                } else {
                    $td.attr('data-checked', 0);
                    $tbody.find('tr').each(function () {
                        var checks = $(this).find('td').eq(index).find('input[type="checkbox"]');
                        if (checks.length > 0) {
                            checks.prop('checked', false);
                          //  checks.iCheck('uncheck');
                        }
                    });
                }
            } else {
                if (flag) {
                    $td.attr('data-checked', 1);
                    $tbody.find('tr').each(function () {
                        var checks = $(this).find('td').eq(index).find('input[type="checkbox"]');
                        if (checks.length > 0) {
                            checks.prop('checked', true);
                           // checks.iCheck('check');
                        }
                    });
                } else {
                    $td.attr('data-checked', 0);
                    $tbody.find('tr').each(function () {
                        var checks = $(this).find('td').eq(index).find('input[type="checkbox"]');
                        if (checks.length > 0) {
                            checks.prop('checked', false);
                          //  checks.iCheck('uncheck');
                        }
                    });
                }
            }
        }

        function tablecheckRow(target, auto, flag) {
            var $this = $(target), $table = $this.parents('table:first');
            var $td = null;
            if ($this.get(0).tagName == 'td') {
                $td = $this;
            } else {
                $td = $this.parents('td:first');
            }
            var $tr = $td.parents('tr:first');
            var checked = $td.attr('data-checked');
            if (!auto) {
                if (!checked || checked == '0') {
                    $td.attr('data-checked', 1);
                    var checks = $tr.find('input[type="checkbox"]');
                    if (checks.length > 0) {
                        checks.prop('checked', true);
                      //  checks.iCheck('check');
                    }
                } else {
                    $td.attr('data-checked', 0);
                    var checks = $tr.find('input[type="checkbox"]');
                    if (checks.length > 0) {
                        checks.prop('checked', false);
                      //  checks.iCheck('uncheck');
                    }
                }
            } else {
                if (flag) {
                    $td.attr('data-checked', 1);
                    var checks = $tr.find('input[type="checkbox"]');
                    if (checks.length > 0) {
                        checks.prop('checked', true);
                       // checks.each(function () {
                       //     $(this).iCheck('check');
                       // })
                    }
                } else {
                    $td.attr('data-checked', 0);
                    var checks = $tr.find('input[type="checkbox"]');
                    if (checks.length > 0) {
                        checks.prop('checked', false);
                     //   checks.iCheck('uncheck');
                    }
                }
            }
        }

        function bindEvent($tb) {
            var $th = $tb.find('.table-header');
            var $tbody = $tb.find('.table-body');
            $tbody.find('tr').each(function () {
                var html = $('#toggleTmpl').html();
                $(this).find('td').eq(0).append($(html));
            });
        }
        //   Xms.Web.Form($('form:first'), function (response) {
        //                Xms.Web.Alert(response.IsSuccess, response.Content);
        //});
    </script>
    <script type="text/html" id="toggleTmpl">
        <div class="pull-right" id="mask_dropdownmenu_7">
            <div class="dropdown">
                <button type="button" class="btn btn-link dropdown-toggle" id="mask_dropdownbtn" data-toggle="dropdown" aria-expanded="true">
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu pull-right" role="menu" style="width:100px;    min-width: 100px;" aria-labelledby="mask_dropdownbtn">
                    <li role="presentation">
                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckRow(this,true,true)">全选</a>
                    </li>
                    <li role="presentation">
                        <a role="menuitem" tabindex="-1" href="javascript:;" onclick="tablecheckRow(this,true,false)">全不选</a>
                    </li>
                </ul>
            </div>
        </div>
    </script>
    <script>

        $(function () {
            var $editform = $('#editform');
            //$editform.on('submit', function () {

            //});

            Xms.Web.Form($editform, function (response) {
               // Xms.Web.Alert(response.IsSuccess, response.Content);
            });
            $editform.find("input[name=RoleObjectAccesses]:not(:disabled)").on('click', null, function () {
                var flag = $(this).prop("checked");
                if (flag) {
                    $editform.find("input[name=RoleObjectAccessId]:not(:disabled)").prop("checked", true);
                    $editform.find("tbody > tr").addClass("active");
                }
                else {
                    $editform.find("input[name=RoleObjectAccessId]:not(:disabled)").removeProp("checked");
                    $editform.find("tbody > tr").removeClass("active");
                }
            });
        });
    </script>
}